package command;

import human.User;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import sun.rmi.runtime.Log;

import jdbc.UserDao;

public class SaveNewUserCommand implements Command {
	private static final Logger log = Logger.getLogger(SaveNewUserCommand.class.getName());
	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) {
		
		String email = req.getParameter("email").trim();
		String password = req.getParameter("password");
		String name = req.getParameter("name");
		String birthDate = req.getParameter("birthDate");
		String cardCode = req.getParameter("cardCode");
		String degree = req.getParameter("degree");
		
		UserDao userDao = new UserDao();
		try {

			userDao.start();

			User user = new User();
			Long l = null;

			if (birthDate.matches("[0-9]+")) {
				user.setBirthDate(Long.parseLong(birthDate));
			}
			if (email
			// .matches("^[A-Za-z0-9.%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,4}"))
			// {
					.matches("[A-Za-z0-9@.%+\\-#%]+")) {
				user.setEmail(email);
			}
			if (password.matches("[A-Za-z0-9@#$%]+")) {
				user.setPassword(password);
			}
			
			user.setName(name);
			user.setCardCode(cardCode);
			user.setDegree(degree);
			
			// Important part here!
			user.setOwnerId((Long)req.getSession(false).getAttribute("userId"));
			userDao.insertUser(user);

			//req.setCharacterEncoding("UTF-8");

			User userToPrint = userDao.selectUserByEmail(email);
			if (userToPrint != null) {
				req.setAttribute("user", userToPrint);

			} else {
				req.setAttribute("user", "Selected null object.");
			}

		} finally {
			userDao.close();
		}
		
		
		return "/addedUser.jspx";
	}

}
